﻿using OA.Model.DB;
using OA.Web.Areas.Admin.Controllers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Web;
using OA.Model;

namespace OA.Web.Areas.Member.Controllers
{
    public class MemberFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var accessor = (IHttpContextAccessor)CallContext.GetData("IHttpContextAccessor");
            string url = string.Empty;
            if (accessor.HttpContext.Request.Method.ToLower() == "get")
            {
                url = "/?url=" + HttpUtility.UrlEncode(accessor.HttpContext.Request.GetEncodedUrl());
            }
            else
            {
                url = "/?url=" + HttpUtility.UrlEncode(accessor.HttpContext.Request.Headers["Referer"].ToString());
            }

            Employee infoEmployee = (Employee)CallContext.GetData("MemberInfo");
            if (infoEmployee == null)
            {
                if (accessor.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                {
                    var result = new { State = 401, Msg = "" };
                    filterContext.Result = new ContentResult() { Content = JsonConvert.SerializeObject(result) };
                }
                else
                {
                    filterContext.Result = new RedirectResult(url);
                }
                return;
            }
            var controller = filterContext.Controller as BaseMemberController;
            if (controller != null)
            {
                controller.ViewBag.IsDepartmentHead = controller.IsDepartmentHead;
                controller.ViewBag.MyMenus = controller.MyMenus;
                controller.ViewBag.Employee = controller.Info;
                controller.ViewBag.EmpName = controller.Info.EmpName;
                controller.ViewBag.EmpID = controller.Info.EmpID;
                controller.ViewBag.Prompt = controller.Prompt;                 
                controller.ViewBag.OssUrl = controller.BaseConfig.OssUrl;
                controller.ViewBag.Signature = controller.Signature;
            }
            base.OnActionExecuting(filterContext);
        }

    }
}